package com.antis.olsl.data.order;

import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewOutlineProvider;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.data.R;
import com.antis.olsl.data.adapter.OrderQueryListAdapter;
import com.antis.olsl.data.databinding.ActivityOrderQueryBinding;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomsOrWarehouseDialog;
import com.antis.olsl.library.response.OrderInfo;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.library.widget.ChooseSalesroomOrWarehouseView;
import com.antis.olsl.library.widget.MyInputSearchLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * @ProjectName: ATS_OLSL
 * @Package: com.antis.olsl.activity.reportLossQuery
 * @ClassName: ReportLossQueryActivity
 * @Description: 订单查询
 * @Author: 羊琪
 * @CreateDate: 2020/4/3 10:08
 * @UpdateDate: 2020/4/3 10:08
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class OrderQueryActivity extends BaseActivity<ActivityOrderQueryBinding> implements ChooseDateDialog.ChooseDateListener,
        View.OnClickListener, ChooseSalesroomsOrWarehouseDialog.ChooseSalesroomOrWarehouseListener,
        MyInputSearchLayout.TextChangedListener, ChooseSalesroomOrWarehouseView.ChooseSalesroomOrWarehouseListener, OnLoadMoreListener {

    OrderQueryListAdapter adapter;
    boolean chooseSalesroom = true;
    ArrayList<OrderInfo> infos = new ArrayList<>();
    ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    ArrayList<SalesroomOrWarehouseInfo> warehouseInfos = new ArrayList<>();
    ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();
    ArrayList<SalesroomOrWarehouseInfo> selectedWarehouseInfos = new ArrayList<>();

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

    Date startDate;
    Date endDate;
    int pageNum = 1;
    int maxPage = 1;
    boolean chooseAllSalesroom = true;
    boolean chooseAllWarehouse = true;
    ChooseSalesroomsOrWarehouseDialog chooseSalesroomsOrWarehouseDialog;
    ChooseDateDialog chooseDateDialog;
    String searchText = "";

    @Override
    protected ActivityOrderQueryBinding getViewBinding() {
        return ActivityOrderQueryBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initViews() {
        setSupportActionBar(viewBinding.toolbar);
        //去掉上滑时顶部阴影
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            viewBinding.appBarLayout.setOutlineProvider(null);
            viewBinding.coordinatorLayout.setOutlineProvider(ViewOutlineProvider.BOUNDS);
        }
        viewBinding.layoutSearchInput.myInputSearchLayout.setHintText("请输入订单号");
        viewBinding.layoutSearchInput.myInputSearchLayout.setListener(this);
        adapter = new OrderQueryListAdapter(infos);
        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.recyclerView.setAdapter(adapter);
        adapter.getLoadMoreModule().setOnLoadMoreListener(this);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Bundle bundle = new Bundle();
//                bundle.putBoolean(ConstantsPool.FROM_SALESROOM_OR_WAREHOUSE, chooseSalesroom);
//                bundle.putString(ConstantsPool.PURCHASE_SLIP_ID, infos.get(position).getOrderNumber());
//                readyGo(OrderQueryDetailsActivity.class, bundle);
            }
        });

        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setChooseSalesroomOrWarehouseListener(this);
        initDate();
        changeChooseType();

        viewBinding.imgBack.setOnClickListener(this);
        viewBinding.tvSalesroom.setOnClickListener(this);
        viewBinding.tvWarehouse.setOnClickListener(this);
        viewBinding.rlChooseDate.setOnClickListener(this);
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        calendar.add(Calendar.DATE, -7);//初始进来查询近7天的数据
        startDate = calendar.getTime();
        setDateText();
    }

    /**
     * 修改类型
     */
    private void changeChooseType() {
        viewBinding.tvSalesroom.setSelected(chooseSalesroom);
        viewBinding.tvWarehouse.setSelected(!chooseSalesroom);
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroom(chooseSalesroom);
        pageNum = 1;
        flushData();
    }

    private void setDateText() {
        viewBinding.tvDate.setText(textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate));
    }

    /**
     * 刷新数据和UI
     */
    private void flushData() {
        ArrayList<SalesroomOrWarehouseInfo> infos = chooseSalesroom ? (chooseAllSalesroom ? salesroomInfos : selectedSalesroomInfos) : (chooseAllWarehouse ? warehouseInfos : selectedWarehouseInfos);
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {

            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            if ((chooseSalesroom && chooseAllSalesroom) || (!chooseSalesroom && chooseAllWarehouse)) {
                continue;
            }
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }
        boolean chooseALL = false;
        if ((chooseSalesroom && chooseAllSalesroom) || (!chooseSalesroom && chooseAllWarehouse)) {
            name = chooseSalesroom ? "全部门店" : "全部仓库";
            chooseALL = true;
        }
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(chooseALL ? null : infos);
        getReportLossSlipList(ids);
    }

    private void getReportLossSlipList(String ids) {
        HashMap<String, Object> map = new HashMap<>();
//        map.put("userId", MyApplication.getUserInfo().getUserId());
//        map.put("flag", chooseSalesroom ? (chooseAllSalesroom ? 1 : 0) : (chooseAllWarehouse ? 0 : 1));//是否为全部门店数据 1是 0否
        map.put("orderNumber", searchText);//输入的关键字查询
        if (chooseSalesroom) {
            map.put("salesroomIds", chooseAllSalesroom ? "" : ids);
        } else {
            map.put("warehouseIds", chooseAllWarehouse ? "" : ids);
        }
        map.put("startDate", simpleDateFormat.format(startDate));
        map.put("endDate", simpleDateFormat.format(endDate));
        map.put("pageNum", pageNum);
        map.put("pageSize", 10);
        // okHttpClient.postJsonObjectParams(chooseSalesroom ? UrlServerConnections.GET_ORDER_QUERY_LIST : UrlServerConnections.GET_ORDER_QUERY_LIST, map, GetOrderQueryListRes.class);
    }

    @Override
    protected void initData() throws IllegalAccessException {

    }

//    @Override
//    public void successResponse(BaseRes baseRes) {
//        if (baseRes instanceof GetSalesroomOrWarehouseListRes) {//获取所有门店或者仓库
//            GetSalesroomOrWarehouseListRes salesroomOrWarehouseListRes = (GetSalesroomOrWarehouseListRes) baseRes;
//            if (chooseSalesroom) {
//                salesroomInfos = salesroomOrWarehouseListRes.getContent();
//            } else {
//                warehouseInfos = salesroomOrWarehouseListRes.getContent();
//            }
//            chooseSalesroomsOrWarehouseDialog = new ChooseSalesroomsOrWarehouseDialog(mContext, chooseSalesroom ? 0 : 1, chooseSalesroom ? salesroomInfos : warehouseInfos, OrderQueryActivity.this);
//        } else if (baseRes instanceof GetOrderQueryListRes) {
//            GetOrderQueryListRes slipListRes = (GetOrderQueryListRes) baseRes;
//            GetOrderQueryListData listData = slipListRes.getContent();
//            if (pageNum == 1) {
//                infos.clear();
//            }
//            maxPage = listData.getTotal() % 10 == 0 ? listData.getTotal() / 10 : listData.getTotal() / 10 + 1;
//            if (listData.getObject() != null) {
//                infos.addAll(listData.getObject());
//            }
//            adapter.setList(infos);
//            adapter.getLoadMoreModule().setEnableLoadMore(pageNum < maxPage);
//            if (pageNum >= maxPage) {
//                adapter.getLoadMoreModule().loadMoreEnd(false);
//            }
//            adapter.getLoadMoreModule().loadMoreComplete();
//        }
//    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_back) {
            onBackPressed();
        } else if (id == R.id.tv_salesroom) {
            if (chooseSalesroom) {
                return;
            }
            chooseSalesroom = true;
            changeChooseType();
        } else if (id == R.id.tv_warehouse) {
            if (!chooseSalesroom) {
                return;
            }
            chooseSalesroom = false;
            changeChooseType();
        } else if (id == R.id.rl_chooseDate) {
            chooseDateDialog = new ChooseDateDialog(this, "选择开始时间", startDate, this, "startDate");
        }
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this, "选择时间不能超过当前时间");
            return;
        }
        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this, "选择结束时间", endDate, this, "endDate");

        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this, "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            pageNum = 1;
            flushData();
        }
        setDateText();
    }

    @Override
    public void onChooseSalesroomOrWarehouseListener(boolean ischooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        if (chooseSalesroom) {
            chooseAllSalesroom = ischooseAll;
            selectedSalesroomInfos = choosedFiledInfos;
            salesroomInfos = sourceInofs;
        } else {
            chooseAllWarehouse = ischooseAll;
            selectedWarehouseInfos = choosedFiledInfos;
            warehouseInfos = sourceInofs;
        }
        pageNum = 1;
        flushData();
    }

    @Override
    public void onTextChangeListener(String text) {
        pageNum = 1;
        searchText = text;
        flushData();
    }

    @Override
    public void clickChooseListener() {
        if (chooseSalesroom) {
            if (salesroomInfos == null || salesroomInfos.size() == 0) {
                getSalesroomOrWareList();
            } else {
                chooseSalesroomsOrWarehouseDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, OrderQueryActivity.this);
            }
        } else {
            if (warehouseInfos == null || warehouseInfos.size() == 0) {
                getSalesroomOrWareList();
            } else {
                chooseSalesroomsOrWarehouseDialog = new ChooseSalesroomsOrWarehouseDialog(this, 1, warehouseInfos, OrderQueryActivity.this);
            }
        }
    }

    /**
     * 获取门店或仓库列表
     */
    private void getSalesroomOrWareList() {
        HashMap<String, Object> map = new HashMap<>();
//        map.put("userId", MyApplication.getUserInfo().getUserId());
        // okHttpClient.postJsonObjectParams(chooseSalesroom ? UrlServerConnections.GET_SALESROOM_LIST : UrlServerConnections.GET_WAREHOUSE_LIST, map, GetSalesroomOrWarehouseListRes.class);
    }

    @Override
    public void clickPhone(String phone) {
    }

    @Override
    public void onLoadMore() {
        if (pageNum == 1) {
            adapter.getLoadMoreModule().setEnableLoadMore(false);
        }
        if (pageNum < maxPage) {
            pageNum++;
            flushData();

        } else {
            adapter.getLoadMoreModule().loadMoreEnd(false);
        }
    }
}
